import { message } from "antd";
import { useEffect, useRef, useState } from "react";
import { FodlerInput } from "./styled";
import { updateName, addFolder } from "@/api/folder";

const TextArea = ({ state, index, dispatch, name }) => {
  let [fileName, setFileName] = useState(name);
  const { folderList, isNewBuild } = state;
  const textareaNode = useRef(null);

  useEffect(() => {
    textareaNode.current.focus();
    textareaNode.current.select();
  }, []);

  const changeName = (e) => {
    setFileName(e.target.value);
  };

  const handleBlur = async () => {
    const folder = folderList[index];
    const name = folder.name;
    const fid = folder.fid;
    const uid = sessionStorage.getItem("uid");
    folder.name = fileName;

    const isfolder = folderList.find(
      (item) => item.name === fileName && item.fid !== fid
    );

    if (isfolder) {
      message.warn("名字重复！");
      setFileName(name);
      return;
    }

    if (isNewBuild) {
      delete folder["fid"];
      await addFolder(folder);
      dispatch({
        type: "explorRequest",
        isNewBuild: false,
      });
    } else {
      dispatch({
        type: "setState",
        payload: {
          folderList,
        },
      });
      // 改变就更新更新数据库数据
      await updateName({
        uid,
        fid,
        name: fileName,
      });
    }
  };
  return (
    <FodlerInput
      ref={textareaNode}
      onBlur={handleBlur}
      onChange={changeName}
      value={fileName}
    />
  );
};

export default TextArea;
